/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ipfms.stripes.report;

import com.google.inject.Inject;
import ipfms.stripes.BaseActionBean;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.cfg.Settings;
import org.hibernate.impl.SessionFactoryImpl;

/**
 *
 * @author fikri
 */
@UrlBinding("/report")
public class ReportAction extends BaseActionBean {

    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    private static final Logger LOGGER = Logger.getLogger(ReportAction.class);

    @DefaultHandler
    public Resolution view() {

        String reportPath = "/home/fikri/Werks/report/";
        String reportName = "jmbSuratSijilJMB.jasper";

        Connection conn = null;

        byte[] bytes = null;

        try {

            conn = getConnection();

            File file = new File(reportPath + reportName);

            bytes = JasperRunManager.runReportToPdf(file.getPath(), null, conn);

            LOGGER.info("bytes " + bytes.length);

        } catch (Exception ex) {
            LOGGER.error(ex);
        }
        
        final byte[] b = bytes;

        return new StreamingResolution("application/pdf") {

            @Override
            public void stream(HttpServletResponse response) throws Exception {
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                response.setHeader("Content-disposition", "inline; filename=test.pdf");
                ServletOutputStream out = response.getOutputStream();
                out.write(b, 0, b.length);
                out.flush();
                out.close();
                
            }
        };
    }

    private Connection getConnection() throws SQLException {
        Settings settings = ((SessionFactoryImpl) sessionProvider.get().getSessionFactory()).getSettings();
        Connection c = settings.getConnectionProvider().getConnection();
        LOGGER.info("got connection.." + c.getClass());
        return c;
    }
}
